var requestManager = require('../../../utils/requestManager.js')
var util = require('../../../utils/util.js')

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityDataList: [],
    nextUrl: '',
    toolDataList: [
      {
        'image': 'https://extend.qnssl.xuemei99.com/icon_pc_delete.png',
        'text': '删除'
      },
      {
        'image': 'https://extend.qnssl.xuemei99.com/icon_pc_shangjia.png',
        'text': '上架'
      },
      {
        'image': 'https://extend.qnssl.xuemei99.com/icon_pc_edit.png',
        'text': '编辑'
      },
      {
        'image': 'https://extend.qnssl.xuemei99.com/icon_pc_hexiao.png',
        'text': '核销'
      }
    ]
  },
  /////////////// 公有方法 ///////////////
  /** 
   * 将网络请求活动数据转化成UI需要的数据模型数组
   */
  resArrayConverToObjectList: function (resArray, dataArray) {
    for (var i = 0; i < resArray.length; i++) {
      let dic = resArray[i];
      
      let startTime = util.formatUTCDateByFormatStr(dic["start_time"], 'YYYY-MM-DD HH:mm')
      let endTime = util.formatUTCDateByFormatStr(dic["end_time"], 'YYYY-MM-DD HH:mm')
      var activityData = {
        "id": dic["id"],
        'title': dic["title"],
        'startTime': startTime,
        'endTime': endTime,
        'imageUrl': dic['image_url'],
        'peopleCount': dic['apply_people_number'],
        'lookCount': dic['attention'],
        'productStatue': dic['product_status'],
        'shelve': dic['shelve']
      }
      dataArray.push(activityData);
    }
  },

  /////////////// 公有方法 ///////////////

  /////////////// 网络请求 ///////////////
  /** 
   * 活动列表
   * shopId 店铺id
   */
  requestActivityList: function(shopId) {
    var that = this
    // 加载活动列表
    requestManager.getRequest('apply/little/apply/product/list/shop', {}, function (res) {
      console.log(res)
      let status = res.status;
      if (status == 0) {
        let array = res.results
        var activityArray = []
        that.data.nextUrl = res.next
        // 将网络请求活动数据转化成UI需要的数据模型数组
        that.resArrayConverToObjectList(array, activityArray)
        console.log(activityArray)
        // 更新UI
        that.setData({
          activityDataList: activityArray
        })
      }
    })
  },

  /**
   * 删除活动
   * activityId 活动id
   * selectIndex 当前选中数据的对应下标
   */
  requestDelegateActivity: function (activityId, selectIndex) {
    var that = this
    requestManager.postRequest('apply/little/apply/product/delete?id=' + activityId, {}, function (res) {
      let status = res.status;
      if (status == 0) {
        // 删除成功
        wx.showToast({
          title: '删除活动成功！',
          icon: 'none'
        })
        // 取出本地活动列表
        var activityDataArray = that.data.activityDataList
        // 删除选中的活动
        activityDataArray.splice(selectIndex, 1)
        that.setData({
          activityDataList: activityDataArray
        })
      }
    })
  },

  /** 
   * 活动上架、下架
   * activityId 活动id
   * selectIndex 当前选中数据的对应下标
   */
  requestShangJiaOrXiajia: function (activityId, selectIndex) {
    var that = this
    requestManager.postRequest('apply/little/apply/product/shelve?id=' + activityId, {}, function (res) {
      let status = res.status
      if (status == 0) {
        // 操作成功
        let shelve = !(that.data.activityDataList[selectIndex].shelve)
        var title = '下架成功！'
        if(shelve) {
          title = '上架成功！'
        }
        wx.showToast({
          title: title,
          icon: 'none'
        })
        // 设置本地数组的上架或下架状态
        let key = 'activityDataList[' + selectIndex + '].shelve'
        that.setData({
          [key]: shelve
        })
      }
    })
  },

  /**
   * 上拉加载请求
   */
  requestNextActivityList: function (nextUrl) {
    var that = this
    console.log('nextUrl' + nextUrl)
    let hasff = 'https://wx.extend.xuemei99.com/'
    let next = nextUrl.substring(hasff.length)

    requestManager.getRequest(next, {}, function (res) {
      let status = res.status
      if (status == 0) {
        let array = res.results
        var activityArray = that.data.activityDataList
        that.data.nextUrl = res.next
        // 将网络请求活动数据转化成UI需要的数据模型数组
        that.resArrayConverToObjectList(array, activityArray)
        // 更新UI
        that.setData({
          recruitmentDataList: recruitmentArray
        })
      }
    })
  },
  /////////////// 网络请求 ///////////////

  /////////////// 事件 ///////////////
  /* 新建活动 */ 
  addActivityTap : function (event) {
    wx.navigateTo({
      url: '/pages/editView/signUp/newWeiActivity',
    })
  },

  /* tool tap事件 */ 
  toolViewTap: function (event) {
    let that = this;
    let tooltext = event.currentTarget.dataset.text;
    let activityId = event.currentTarget.dataset.id;
    let index = event.currentTarget.dataset.index;
    switch (tooltext) {
      case '删除':
        {
          wx.showModal({
            title: '提示',
            content: '确定删除嘛?',
            success:function(del_ress){
              if (del_ress.confirm) {
                that.requestDelegateActivity(activityId, index)
                console.log('用户点击确定')
              } else if (del_ress.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
        break;
      case '下架':
        {
          this.requestShangJiaOrXiajia(activityId, index)
        }
        break;
      case '上架':
        {
          this.requestShangJiaOrXiajia(activityId, index)
        }
        break;
      case '编辑':
        {         
          wx.navigateTo({
            url: '/pages/editView/signUp/newWeiActivity?activity_id=' + activityId,
          })
        }
        break;
      case '核销':
        {
          wx.navigateTo({
            url: '/pages/editView/personalCenter/activityHeXiao?activity_id=' + activityId,
          })
        }
        break;
    }
  },
  /////////////// 事件 ///////////////

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var shopId = app.globalData.shop_id
    this.requestActivityList(shopId);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉刷新')
    this.requestRecruitmentList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('上拉加载')
    let tNextUrl = this.data.nextUrl
    if (tNextUrl && tNextUrl.length > 0) {
      this.requestNextActivityList(tNextUrl)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})